package ccm.component.oscilloscope;

import ccm.common.BufferManager;
import ccm.common.Crc;
import ccm.common.ReceiveDataEvent;

public class JustFloatDataManager extends VisualScopeDataManager
{

    public JustFloatDataManager()
    {
        super();
        receiveBuf=new int[10240];
    }


    /**
     * 获取一共有几列
     *
     * @return 列数
     */
    public int getDataColumn()
    {
        return 20;
    }

    /**
     * 获取第i行数据第column列是不是可用的数据点
     *
     * @param i      数据行
     * @param column 数据列
     * @return 是否可用
     */
    public boolean isColumnEnabled(int i,int column)
    {
        if(data.get(i)==null)
            return false;
        return column<data.get(i).length;
    }

    /**
     * 获取纵坐标
     *
     * @param i      数据行
     * @param column 数据列
     * @return 纵坐标
     */
    public float getY(int i,int column)
    {
        float[] tmp=data.get(i);
        return column<tmp.length?tmp[column]:0;
    }

    /**
     * 接收到数据事件
     */
    synchronized public void receiveData(ReceiveDataEvent event)
    {
        for(byte datum: event.getData())
        {
            receiveBuf[receiveBufStart]=Byte.toUnsignedInt(datum);
            receiveBufStart            =(receiveBufStart+1)%receiveBuf.length;
            final int tailLength=4+4+2;
            if(receiveBufStart>=tailLength&&(receiveBufStart-tailLength)%4==0&&BufferManager.getUint8(receiveBuf,receiveBufStart-tailLength)==0X00&&BufferManager.getUint8(receiveBuf,receiveBufStart-tailLength+1)==0X00&&BufferManager.getUint8(receiveBuf,receiveBufStart-tailLength+2)==0x80&&BufferManager.getUint8(receiveBuf,receiveBufStart-tailLength+3)==0x7f)
            {
                if(BufferManager.getUint16(receiveBuf,receiveBufStart-2)==Crc.crc16Modbus(receiveBuf,0,receiveBufStart-2))
                {
                    //System.out.println("JustFloatDataManager receiveData success "+receiveBufStart);
                    float[] ans=new float[((receiveBufStart-tailLength)/4)];
                    for(int i=0;i<ans.length;++i)
                        ans[i]=Float.intBitsToFloat((int)BufferManager.getUint32(receiveBuf,i*4));
                    final long timeOrigin=BufferManager.getUint32(receiveBuf,receiveBufStart-tailLength+4);
                    //final long time=(timeOrigin&0X7FFF)|(event.getTimeUs()-(((event.getTimeUs()&0X8000L)!=(timeOrigin&0X8000L))?0X8000L:0L))&0XFFFFFFFFFFFF8000L;
                    final long time=(timeOrigin&0X7FFFFFFF)|(event.getTimeUs()-(((event.getTimeUs()&0X80000000L)!=(timeOrigin&0X80000000L))?0X80000000L:0L))&0XFFFFFFFF80000000L;
                    data.add(ans);
                    timeUs.add(time);
                }
                else
                    System.out.println("JustFloatDataManager receiveData fail "+receiveBufStart);
                receiveBufStart=0;
            }
        }
    }
}
